package com.dg.river.core;

import android.app.Application;
import android.content.Context;

import com.dg.river.contant.Constant;
import com.dg.river.core.http.OkGoUtils;
import com.dg.river.core.http.interceptor.LogInterceptor;
import com.dg.river.core.http.interceptor.TokenInterceptor;
import com.dg.river.core.manager.UserInfoManager;
import com.dg.river.core.util.FileUtils;
import com.dg.river.core.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.concurrent.TimeUnit;

import me.jessyan.autosize.AutoSizeConfig;
import okhttp3.OkHttpClient;

public class MyApplication extends Application {

    public static IWXAPI wxapi;

    public static MyApplication instance;
    private static Context appContext;

    public static MyApplication getInstance() {
        if (instance == null) {
            synchronized (MyApplication.class) {
                instance = new MyApplication();
            }
        }
        return instance;
    }

    public static Context getAppContext(){
        return  appContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = getBaseContext();
        // 屏幕适配
        AutoSizeConfig.getInstance().setLog(false).setUseDeviceSize(true).setBaseOnWidth(true);
        // Toast工具类初始化
        ToastUtils.getInstance().init(this);
        // 用户信息存储
        UserInfoManager.getInstance().init(this);
        // OkGo初始化
        initOkGo();
        // OkGoUtils初始化
        OkGoUtils.getInstance().init(getApplicationContext());
        // OkGoUtils初始化
        OkGoUtils.getInstance().init(getApplicationContext());
        // 微信注册
        wxapi = WXAPIFactory.createWXAPI(this, Constant.WEXIN_KEY, true);
        wxapi.registerApp(Constant.WEXIN_KEY);
    }

    private void initOkGo() {
        // 一、OkHttpClientBuilder
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // 全局的读取超时时间
        builder.readTimeout(5000, TimeUnit.MILLISECONDS);
        // 全局的写入超时时间
        builder.writeTimeout(5000, TimeUnit.MILLISECONDS);
        // 全局的连接超时时间
        builder.connectTimeout(3000, TimeUnit.MILLISECONDS);
        // Token拦截器
        builder.addInterceptor(new TokenInterceptor(this));
        // 日志拦截器
        builder.addInterceptor(new LogInterceptor());
        // 二、公共HttpHeaders
        HttpHeaders httpHeaders = new HttpHeaders();
        // 三、OkGo配置
        OkGo.getInstance()
                .init(this)
                .setOkHttpClient(builder.build())
                .setRetryCount(0)
                .addCommonHeaders(httpHeaders);
    }
}
